<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search" />
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          size="small"
          @click="handleSearchList()"
        >
          查询搜索
        </el-button>
        <el-button
          type="primary"
          style="float:right;margin-right: 15px"
          size="small"
          @click="handleResetSearch()"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="轮播名称：">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="轮播名称" />
          </el-form-item>
          <el-form-item label="轮播位置：">
            <el-select v-model="listQuery.type" placeholder="全部" clearable class="input-width">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets" />
      <span>轮播数据</span>
      <el-button size="mini" class="btn-add" style="float: right" type="primary" @click="handleAdd()">添加轮播</el-button>
    </el-card>
    <div class="table-container">
      <el-table
        ref="homeAdvertiseTable"
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        style="width: 100%;"
        border
        highlight-current-row
        fit
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column
          type="selection"
          width="60"
          align="center"
        />
        <el-table-column label="编号" prop="id" width="100" sortable="custom" align="center" :class-name="getSortClass('id')">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="轮播名称" align="center" width="200">
          <template slot-scope="scope">{{ scope.row.title }}</template>
        </el-table-column>
        <el-table-column label="轮播位置" width="160" align="center">
          <template slot-scope="scope">{{ scope.row.type | formatType }}</template>
        </el-table-column>
        <el-table-column label="轮播图片" width="350" align="center">
          <template slot-scope="scope"><img style="height: 100px" :src="scope.row.pic"></template>
        </el-table-column>

        <el-table-column label="图片尺寸" width="147" align="center">
          <template slot-scope="scope">{{ scope.row.width }}*{{ scope.row.height }}</template>
        </el-table-column>
        <el-table-column label="时间" width="260" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.createTime | formatTime }}</p>

          </template>
        </el-table-column>

        <el-table-column label="启用" width="120" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleUpdateStatus(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="223" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleUpdate(scope.$index, scope.row)"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
      <el-select
        v-model="operateType"
        size="small"
        placeholder="批量操作"
      >
        <el-option
          v-for="item in operates"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button
        style="margin-left: 20px"
        class="search-button"
        type="primary"
        size="small"
        @click="handleBatchOperate()"
      >
        确定
      </el-button>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15]"
        :current-page.sync="listQuery.pageNum"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<script>

  import { fetchList, updateStatus, deleteHomeAdvertise, batchDeleteHomeAdvertise } from '@/api/system/homeAdvertise';
  import { formatDate } from '@/utils/date';
  const defaultListQuery = {
      pageIndex: 1,
      pageSize: 5,
      keyword: '',
      type: '',
      pageSorts: []
  };
  const defaultStatus = {
    id: '',
    status: ''
  };
  const defaultTypeOptions = [
    {
      label: 'PC首页轮播',
      value: "0"
    },
    {
      label: 'APP首页轮播',
      value: "1"
    }
  ];
  export default {
    name: 'HomeAdvertiseList',
    filters: {
      formatType(type) {
        if (type === "1") {
          return 'APP首页轮播';
        } else {
          return 'PC首页轮播';
        }
      },
      formatTime(time) {
        if (time == null || time === '') {
          return 'N/A';
        }
        const date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    data() {
      return {
        tableKey: 0,
        listQuery: Object.assign({}, defaultListQuery),
        typeOptions: Object.assign({}, defaultTypeOptions),
        updateAdvertiseStatus: Object.assign({}, defaultStatus),
        list: null,
        total: null,
        listLoading: false,
        multipleSelection: [],
        sortAsc: false,
        sortColumn: 'id',
        searchColumn: 'keyword',
        searchValue: null,
        operates: [
          {
            label: "删除",
            value: 0
          }
        ],
        operateType: null
      }
    },
    created() {
      this.setDefaultSort()
      this.getList();
    },
    methods: {

        setDefaultSort() {
            // 设置默认排序
            this.listQuery.pageSorts = [{
                column: this.sortColumn,
                asc: this.sortAsc
            }]
        },
        sortChange(data) {
            const { prop, order } = data
            if (prop === 'createTime') {
                this.sortColumn = 'create_time'
            } else {
                this.sortColumn = prop
            }
            this.sortAsc = order === 'ascending'
            this.listQuery.pageSorts = [{
                column: this.sortColumn,
                asc: this.sortAsc
            }]
            this.handleFilter()
        },

        getSortClass: function(key) {
            if (this.sortColumn === key) {
                return this.sortAsc ? 'ascending' : 'descending'
            } else {
                return ''
            }
        },
        handleResetSearch() {
            this.listQuery = Object.assign({}, defaultListQuery);
            this.getList();
        },

        handleFilter() {
            this.listQuery.pageIndex = 1
            this.listQuery.keyword = null;
            this.listQuery[this.searchColumn] = this.searchValue;
            this.getList()
        },
        // 处理搜索列表
      handleSearchList() {
        this.listQuery.pageIndex = 1;
        this.getList();
      },
        // 处理处理选择改变
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },

      handleSizeChange(val) {
        this.listQuery.pageIndex = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageIndex = val;
        this.getList();
      },
      handleUpdateStatus(index, row) {
          this.updateAdvertiseStatus.id = row.id;
          this.updateAdvertiseStatus.status = row.status;
          this.$confirm('是否要启用?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStatus(this.updateAdvertiseStatus).then(response => {
              console.log(response)
            this.$message({
              type: 'success',
              message: '修改轮播信息成功!'
            });
              this.getList();
          });
        }).catch(() => {
          this.$message({
            type: 'success',
            message: '已取消操作!'
          });
          this.getList();
        });
      },
      handleDelete(index, row) {
        this.deleteHomeAdvertise(row.id);
      },
      handleBatchOperate() {
        if (this.multipleSelection < 1) {
          this.$message({
            message: '请选择一条记录',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        const ids = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id);
        }
        if (this.operateType === 0) {
          // 批量删除
            batchDeleteHomeAdvertise(ids).then(response => {
                this.getList();
                this.$message({
                    type: 'success',
                    message: '删除轮播信息成功!'
                });
            });
        } else {
          this.$message({
            message: '请选择批量操作类型',
            type: 'warning',
            duration: 1000
          });
        }
      },
      handleAdd() {
        this.$router.push({ path: '/system/config/addAdvertise' })
      },
      handleUpdate(index, row) {
        this.$router.push({ path: '/system/config/updateAdvertise', query: { id: row.id }})
      },
      getList() {
        this.listLoading = true;
        fetchList(this.listQuery).then(response => {
          this.listLoading = false;
          this.list = response.data.records;
          this.total = response.data.total;
        })
      },
      deleteHomeAdvertise(ids) {
        this.$confirm('是否要删除该广告?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // const params = new URLSearchParams();
          // params.append("ids", ids);
          deleteHomeAdvertise(ids).then(response => {
            this.getList();
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          });
        })
      }
    }
  }
</script>
<style scoped>
  .input-width {
    width: 203px;
  }
</style>


